package com.example.controller;

import com.example.model.ApiResponse;
import com.example.model.ChatRequest;
import com.example.service.AiService;
import com.example.service.impl.GuijiAiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AiController {
    private final List<AiService> aiServices;
    private final GuijiAiService guijiAiService;

    @GetMapping("/generate")
    public ApiResponse generateCode(
            @RequestParam String prompt,
            @RequestParam(required = false) String sessionId) {
        try {
            // URL解码处理
            prompt = URLDecoder.decode(prompt, StandardCharsets.UTF_8.name());
            String response = guijiAiService.generateResponse(prompt, sessionId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error("生成代码失败: " + e.getMessage());
        }
    }

    @GetMapping(value = "/generate/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStream(
            @RequestParam String prompt,
            @RequestParam(required = false) String sessionId) {
        try {
            // URL解码处理
            prompt = URLDecoder.decode(prompt, StandardCharsets.UTF_8.name());
            return guijiAiService.generateStreamResponse(prompt, sessionId);
        } catch (Exception e) {
            return Flux.just(e.getMessage());
        }
    }

    @PostMapping("/chat")
    public ApiResponse chat(
            @RequestBody(required = false) ChatRequest request,
            @RequestParam(required = false) String prompt,
            @RequestParam(required = false, defaultValue = "0") Integer serviceIndex,
            @RequestParam(required = false) String sessionId) {
        
        try {
            // 如果请求体为空，使用URL参数
            if (request == null) {
                if (prompt == null) {
                    return ApiResponse.error("prompt参数不能为空");
                }
                // URL解码处理
                try {
                    prompt = URLDecoder.decode(prompt, StandardCharsets.UTF_8.name());
                } catch (Exception e) {
                    return ApiResponse.error("prompt参数解码失败: " + e.getMessage());
                }
                request = new ChatRequest();
                request.setPrompt(prompt);
                request.setServiceIndex(serviceIndex);
            }

            if (request.getServiceIndex() < 0 || request.getServiceIndex() >= aiServices.size()) {
                return ApiResponse.error("无效的服务索引");
            }
            
            String response = aiServices.get(request.getServiceIndex()).generateResponse(request.getPrompt(), sessionId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error("处理请求失败: " + e.getMessage());
        }
    }

    @PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chatStream(
            @RequestBody(required = false) ChatRequest request,
            @RequestParam(required = false) String prompt,
            @RequestParam(required = false, defaultValue = "0") Integer serviceIndex,
            @RequestParam(required = false) String sessionId) {
        
        try {
            // 如果请求体为空，使用URL参数
            if (request == null) {
                if (prompt == null) {
                    return Flux.just("prompt参数不能为空");
                }
                // URL解码处理
                try {
                    prompt = URLDecoder.decode(prompt, StandardCharsets.UTF_8.name());
                } catch (Exception e) {
                    return Flux.just("prompt参数解码失败: " + e.getMessage());
                }
                request = new ChatRequest();
                request.setPrompt(prompt);
                request.setServiceIndex(serviceIndex);
            }

            if (request.getServiceIndex() < 0 || request.getServiceIndex() >= aiServices.size()) {
                return Flux.just("无效的服务索引");
            }
            
            return aiServices.get(request.getServiceIndex()).generateStreamResponse(request.getPrompt(), sessionId);
        } catch (Exception e) {
            return Flux.just(e.getMessage());
        }
    }

    @PostMapping("/clear-history")
    public ApiResponse clearHistory(@RequestParam String sessionId) {
        try {
            guijiAiService.clearHistory(sessionId);
            return ApiResponse.success("会话历史已清除");
        } catch (Exception e) {
            return ApiResponse.error("清除会话历史失败: " + e.getMessage());
        }
    }
} 